#include "pch.h"
#include "cconfigurer.h"
#include "Plugins/initReader/SimpleIni.h"
#include "Plugins/dirHelper/cDirHelper.h"

namespace libtool_sdk
{

	cConfigurer::cConfigurer():
		m_bInit(false)
	{
		memset(m_strIniFile, 0, sizeof(m_strIniFile));
	}

	cConfigurer::~cConfigurer()
	{
		m_iniParser.Reset();
		m_bInit = false;
	}

	bool cConfigurer::loadIniFile(const char *fileName)
	{
		if (!Helper::Tool_checkFileOrDirExsit(fileName))
		{
			fprintf(stderr, "file %s is not exsit.\n",fileName);
			return false;
		}

		SI_Error rc = m_iniParser.LoadFile(fileName);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "laod file %s failed.\n", fileName);
			return false;
		};
		strcpy(m_strIniFile, fileName);

		m_bInit = true;
		return true;
	}

	void cConfigurer::createIniFile(const char *fileName)
	{
		std::string strNodeMap;
		strNodeMap.append("[default]\nkey = value\n");
		SI_Error rc = m_iniParser.LoadData(strNodeMap);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "LoadData failed.\n");
		};

		rc = m_iniParser.SaveFile(fileName);
		if (rc < 0)
		{ /* handle error */
			fprintf(stderr, "create IniFile %s failed.\n", fileName);
		};
	}

	bool cConfigurer::get_section_value(const char* sectionName, const char* keyName, char* valueBuf, int* bufLen)
	{
		if(!m_bInit)
		{
			fprintf(stderr, "please load ini file first.\n");
			return false;
		}
		if (valueBuf == NULL || bufLen == NULL)
		{
            fprintf(stderr, "please check the param.\n");
            return false;
		}

		const char *pchValue = NULL;
		pchValue = m_iniParser.GetValue(sectionName, keyName, "0");
		if (pchValue != NULL)
		{
			size_t iBufLen = *bufLen;
#ifdef _WIN32
			*bufLen = _snprintf(valueBuf, iBufLen, "%s", pchValue);
#else
			*bufLen = snprintf(valueBuf, iBufLen, "%s", pchValue);
#endif
		}

		return (pchValue == NULL ) ? false : true;
	}

	bool cConfigurer::set_section_value(const char* sectionName, const char* keyName, const char* value)
	{
		if(!m_bInit)
		{
			fprintf(stderr, "please load ini file first.\n");
			return false;
		}

		m_iniParser.SetValue(sectionName, keyName, value);
		SI_Error rc = m_iniParser.SaveFile(m_strIniFile);
		if (rc < 0)
		{
			/* handle error */
			fprintf(stderr, "save to  file failed.\n");
			return false;
		};
		m_iniParser.Reset();
		m_bInit = false;

		loadIniFile(m_strIniFile);
		return true;
	}

	bool cConfigurer::get_section_value_int(const char * sectionName, const char * keyName, int * value)
	{
		char chBuf[256] = {0};
		int iBufLen = sizeof(chBuf);
		if(get_section_value(sectionName, keyName, chBuf, &iBufLen))
		{
			*value = atoi(chBuf);
			return true;
		}
		else
		{
			return false;
		}
	}

	bool cConfigurer::set_section_value_int(const char *sectionName, const char *keyName, int value)
	{
		char chBuf[256] = {0};
		sprintf(chBuf, "%d", value);
		return set_section_value(sectionName, keyName, chBuf);
	}


}
